package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.dao.PurchaseDetailDao;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.PurchaseService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.PurchaseDoneReqVo;
import com.atguigu.gulimall.ware.vo.PurchaseMergeReqVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    PurchaseDetailDao purchaseDetailDao;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询未领取的采购单
     *
     * @return 未领取的采购单
     */
    @Override
    public PageUtils queryUnreceiveList(Map<String, Object> params) {

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
                        .eq("status", WareConstant.PurchaseDetailStatusEnum.CREATE.getCode())
                        .or()
                        .eq("status", WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode())
        );

        return new PageUtils(page);
    }

    /**
     * 合并采购需求
     *
     * @param purchaseMergeReqVo 采购信息请求vo
     */
    @Transactional
    @Override
    public void merge(PurchaseMergeReqVo purchaseMergeReqVo) {
        Long purchaseId = purchaseMergeReqVo.getPurchaseId();
        // 如果合并到新建的采购单
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATE.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        // 批量更新采购需求的采购单id和状态
        List<Long> items = purchaseMergeReqVo.getItems();
        if (CollectionUtils.isEmpty(items)) {
            items = Collections.emptyList();
        }
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> detailEntityList = items.stream().map(item -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(item);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(detailEntityList);

        // 更新采购单时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

    }

    /**
     * 领取采购单
     *
     * @param ids 采购单id列表
     */
    @Override
    public void received(List<Long> ids) {
        // 确认采购单是新建或者已分配状态
        List<PurchaseEntity> purchaseEntityList = baseMapper.selectBatchIds(ids);
        List<PurchaseEntity> collect = purchaseEntityList.stream()
                .filter(entity ->
                        entity.getStatus() == WareConstant.PurchaseStatusEnum.CREATE.getCode()
                                || entity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
                .peek(item -> {
                    item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    item.setUpdateTime(new Date());
                })
                .collect(Collectors.toList());

        // 修改采购单的状态
        this.updateBatchById(collect);

        // 修改采购需求的状态
        List<PurchaseDetailEntity> detailList = new ArrayList<>();
        for (PurchaseEntity purchaseEntity : collect) {
            List<PurchaseDetailEntity> detailEntityList = purchaseDetailDao.selectList(
                    new QueryWrapper<PurchaseDetailEntity>()
                            .eq("purchase_id", purchaseEntity.getId()));
            detailList.addAll(detailEntityList);
        }
        detailList = detailList.stream()
                .peek(item -> item.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode()))
                .collect(Collectors.toList());
        purchaseDetailService.updateBatchById(detailList);

    }

    /**
     * 完成采购
     *
     * @param purchaseDoneReqVo 采购单完成请求vo
     */
    @Override
    public void done(PurchaseDoneReqVo purchaseDoneReqVo) {
        // 更新采购需求
        boolean flag = true;
        List<PurchaseDoneReqVo.PurchaseItemDoneInfo> items = purchaseDoneReqVo.getItems();
        List<PurchaseDetailEntity> detailEntityList = new ArrayList<>();
        for (PurchaseDoneReqVo.PurchaseItemDoneInfo item : items) {
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                flag = false;
            } else {
                // 成功采购需求入库
                PurchaseDetailEntity entity = purchaseDetailDao.selectById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum());
            }
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(item.getItemId());
            detailEntity.setStatus(item.getStatus());
            detailEntityList.add(detailEntity);
        }
        purchaseDetailService.updateBatchById(detailEntityList);

        // 更新采购单
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseDoneReqVo.getId());
        purchaseEntity.setUpdateTime(new Date());
        if (flag) {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
        } else {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        }
        baseMapper.updateById(purchaseEntity);

    }

}